<template>
  <div class="mobile-form-container">
    <div class="form-header">
      <div class="header-bg"></div>
      <div class="header-content">
        <h1>学习记录</h1>
        <p>记录你的每一次进步</p>
      </div>
    </div>

    <div class="form-content">
      <el-form 
        ref="recordFormRef" 
        :model="form" 
        :rules="rules" 
        label-position="top"
        class="mobile-form"
      >
        <!-- 学生信息区域 -->
        <div class="form-section">
          <h3 class="section-title">
            <el-icon><User /></el-icon>
            学生信息
          </h3>
          
          <el-form-item label="学生学号" prop="studentNumber">
            <el-input 
              v-model="form.studentNumber" 
              placeholder="请输入学号"
              class="mobile-input"
              maxlength="20"
              show-word-limit
            >
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="学生姓名" prop="studentName">
            <el-input 
              v-model="form.studentName" 
              placeholder="请输入姓名"
              class="mobile-input"
              maxlength="20"
              show-word-limit
            >
              <template #prefix>
                <el-icon><Avatar /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="学习方向" prop="directionId">
            <el-select 
              v-model="form.directionId" 
              placeholder="请选择学习方向"
              class="mobile-select"
              filterable
              :loading="loadingDirections"
            >
              <el-option
                v-for="item in directionOptions"
                :key="item.directionId"
                :label="item.directionName"
                :value="item.directionId"
              />
            </el-select>
          </el-form-item>
        </div>

        <!-- 学习时间区域 -->
        <div class="form-section">
          <h3 class="section-title">
            <el-icon><Clock /></el-icon>
            学习时间
          </h3>

          <!-- 日期选择 -->


          <!-- 开始时间 -->
          <el-form-item label="开始时间" prop="startTime">
            <el-time-picker
              v-model="startTime"
              placeholder="选择开始时间"
              class="mobile-time"
              format="HH:mm"
              value-format="HH:mm"
              :disabled-hours="disabledStartHours"
              :disabled-minutes="disabledStartMinutes"
            />
          </el-form-item>

          <!-- 结束时间 -->
          <el-form-item label="结束时间" prop="endTime">
            <el-time-picker
              v-model="endTime"
              placeholder="选择结束时间"
              class="mobile-time"
              format="HH:mm"
              value-format="HH:mm"
              :disabled-hours="disabledEndHours"
              :disabled-minutes="disabledEndMinutes"
            />
          </el-form-item>

          <div v-if="studyDuration" class="duration-display">
            <el-icon><Timer /></el-icon>
            学习时长：{{ studyDuration }}
          </div>
        </div>

        <!-- 学习内容区域 -->
        <div class="form-section">
          <h3 class="section-title">
            <el-icon><Document /></el-icon>
            学习内容
          </h3>

          <el-form-item label="学习内容" prop="content">
            <el-input
              v-model="form.content"
              type="textarea"
              placeholder="请详细描述今天的学习内容..."
              class="mobile-textarea"
              :rows="4"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="成果材料" prop="materials">
            <el-upload
              class="mobile-upload"
              drag
              action="#"
              :auto-upload="false"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :file-list="fileList"
              accept=".jpg,.jpeg,.png,.pdf,.doc,.docx"
              :limit="3"
            >
              <el-icon class="upload-icon"><Upload /></el-icon>
              <div class="upload-text">
                <div class="upload-title">拖拽文件到此处或点击上传</div>
                <div class="upload-tip">支持 图片、代码压缩包</div>
              </div>
            </el-upload>
          </el-form-item>
        </div>

        <!-- 位置信息区域 -->
        <div class="form-section">
          <el-form-item label="书桌编号" prop="deskId">
            <el-input 
              v-model="form.deskId" 
              placeholder="请输入位置编号，如：3081,3082"
              class="mobile-input"
              maxlength="10"
            >
            </el-input>
          </el-form-item>
        </div>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <el-button 
            type="primary" 
            class="submit-btn"
            @click="submitForm"
            :loading="submitLoading"
            size="large"
          >
            <el-icon><Check /></el-icon>
            提交学习记录
          </el-button>

          <el-button 
            class="reset-btn"
            @click="resetForm"
            size="large"
          >
            <el-icon><Refresh /></el-icon>
            重置表单
          </el-button>
        </div>
      </el-form>
    </div>

    <!-- 成功提示 -->
    <el-dialog
      v-model="successDialogVisible"
      title="提交成功"
      width="80%"
      center
      class="success-dialog"
    >
      <div class="success-content">
        <el-icon class="success-icon"><CircleCheck /></el-icon>
        <h3>学习记录已提交</h3>
        <p>继续加油，记录每一次进步！</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="successDialogVisible = false">
          知道了
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RecordTime">
import { ref, computed, getCurrentInstance, reactive, onMounted, watch } from 'vue';
import { addRecordTimePublic } from "@/api/analyzemanagement/recordTimePublic";
import { listDirection } from "@/api/directionmanagement/direction";
import { uploadImageFile } from "@/api/tool/oss";
import dayjs from 'dayjs';

const { proxy } = getCurrentInstance();

const recordFormRef = ref();
const submitLoading = ref(false);
const locationLoading = ref(false);
const successDialogVisible = ref(false);
const fileList = ref([]);

// 日期和时间选择器变量
const startTime = ref('');
const endTime = ref('');

// 表单数据
const form = reactive({
  studentNumber: '',
  studentName: '',
  directionId: '',
  studyDate: dayjs().format('YYYY-MM-DD'), // 学习日期，默认为当日
  startTime: '',
  endTime: '',
  content: '',
  result: '',
  deskId: '',
  sumTime: ''
});

// 方向选项
const directionOptions = ref([]);
const loadingDirections = ref(false);

// 表单验证规则
const rules = {
  studentNumber: [
    { required: true, message: '请输入学生学号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  studentName: [
    { required: true, message: '请输入学生姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  directionId: [
    { required: true, message: '请选择学习方向', trigger: 'change' }
  ],
  studyDate: [
    { required: true, message: '请选择学习日期', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入学习内容', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  deskId: [
    { required: true, message: '请输入位置编号', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ]
};



// 监听日期和时间变化，组合成完整的日期时间
const updateStartDateTime = () => {
  if (form.studyDate && startTime.value) {
    form.startTime = `${form.studyDate} ${startTime.value}:00`;
  } else {
    form.startTime = '';
  }
};

const updateEndDateTime = () => {
  if (form.studyDate && endTime.value) {
    form.endTime = `${form.studyDate} ${endTime.value}:00`;
  } else {
    form.endTime = '';
  }
};

// 监听变化
watch([() => form.studyDate, startTime], updateStartDateTime);
watch([() => form.studyDate, endTime], updateEndDateTime);

// 计算学习时长（用于显示）
const studyDuration = computed(() => {
  if (form.startTime && form.endTime) {
    const start = new Date(form.startTime);
    const end = new Date(form.endTime);
    
    if (end > start) {
      const diffMs = end - start;
      const hours = Math.floor(diffMs / (1000 * 60 * 60));
      const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));
      
      if (hours > 0) {
        return `${hours}小时${minutes}分钟`;
      } else {
        return `${minutes}分钟`;
      }
    }
  }
  return '';
});

// 计算学习时长（以分钟为单位，用于提交）
const studyDurationMinutes = computed(() => {
  if (form.startTime && form.endTime) {
    const start = new Date(form.startTime);
    const end = new Date(form.endTime);
    
    if (end > start) {
      const diffMs = end - start;
      const totalMinutes = Math.floor(diffMs / (1000 * 60));
      return totalMinutes;
    }
  }
  return 0;
});

// 禁用日期函数
const disabledDate = (time) => {
  return time.getTime() > Date.now();
};

// 禁用时间函数
const disabledStartHours = () => {
  const now = new Date();
  const currentHour = now.getHours();
  
  // 如果是今天，禁用未来的小时
  if (form.studyDate === formatDate(now)) {
    return Array.from({ length: 24 }, (_, i) => i).filter(hour => hour > currentHour);
  }
  return [];
};

const disabledStartMinutes = (hour) => {
  const now = new Date();
  const currentHour = now.getHours();
  const currentMinute = now.getMinutes();
  
  // 如果是今天且当前小时，禁用未来的分钟
  if (form.studyDate === formatDate(now) && hour === currentHour) {
    return Array.from({ length: 60 }, (_, i) => i).filter(minute => minute > currentMinute);
  }
  return [];
};

const disabledEndHours = () => {
  const now = new Date();
  const currentHour = now.getHours();
  
  // 如果是今天，禁用未来的小时
  if (form.studyDate === formatDate(now)) {
    return Array.from({ length: 24 }, (_, i) => i).filter(hour => hour > currentHour);
  }
  
  // 如果有开始时间，禁用开始时间之前的小时
  if (startTime.value) {
    const [startHour] = startTime.value.split(':').map(Number);
    if (form.studyDate === formatDate(now)) {
      return Array.from({ length: 24 }, (_, i) => i).filter(hour => hour < startHour || hour > currentHour);
    }
    return Array.from({ length: 24 }, (_, i) => i).filter(hour => hour < startHour);
  }
  
  return [];
};

const disabledEndMinutes = (hour) => {
  const now = new Date();
  const currentHour = now.getHours();
  const currentMinute = now.getMinutes();
  
  // 如果是今天且当前小时，禁用未来的分钟
  if (form.studyDate === formatDate(now) && hour === currentHour) {
    return Array.from({ length: 60 }, (_, i) => i).filter(minute => minute > currentMinute);
  }
  
  // 如果有开始时间且在相同小时，禁用开始时间之前的分钟
  if (startTime.value) {
    const [startHour, startMinute] = startTime.value.split(':').map(Number);
    if (hour === startHour) {
      return Array.from({ length: 60 }, (_, i) => i).filter(minute => minute < startMinute);
    }
  }
  
  return [];
};

// 格式化日期函数
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 文件上传处理
const handleFileChange = async (file, files) => {
  // 限制最多3个文件
  if (files.length > 3) {
    files = files.slice(-3);
    fileList.value = files;
    ElMessage.warning('最多只能上传3个文件');
    return;
  }
  
  try {
    // 上传文件 // 打印当前认证token，用于调试
    const response = await uploadImageFile(file.raw);
    
    if (response.code === 200) {
      // 更新文件列表，添加URL
      file.url = response.msg;
      fileList.value = files;
      
      // 将上传后的URL保存到form.result字段
      // 如果已有文件URL，则用逗号分隔
      if (form.result) {
        form.result = form.result + ',' + response.msg;
      } else {
        form.result = response.msg;
      }
      ElMessage.success('文件上传成功');
    } else {
      ElMessage.error('文件上传失败：' + response.msg);
    }
  } catch (error) {
    console.error('文件上传错误:', error);
    ElMessage.error('文件上传失败，请稍后重试');
  }
};

// 文件删除处理
const handleFileRemove = (file, files) => {
  // 更新文件列表
  fileList.value = files;
  
  // 如果文件有URL，则从form.result中移除
  if (file.url) {
    const urls = form.result.split(',');
    const index = urls.indexOf(file.url);
    if (index !== -1) {
      urls.splice(index, 1);
      form.result = urls.join(',');
    }
  }
};


// 提交表单
const submitForm = () => {
  recordFormRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true;
      
      // 设置学习时长（以分钟为单位）
      form.sumTime = studyDurationMinutes.value.toString();
      
      const submitData = {
        ...form,
        duration: studyDuration.value
      };
      
      addRecordTimePublic(submitData)
        .then(() => {
          successDialogVisible.value = true;
          resetForm();
        })
        .catch(() => {
          ElMessage.error('提交失败，请稍后重试');
        })
        .finally(() => {
          submitLoading.value = false;
        });
    }
  });
};

// 加载方向列表
const loadDirectionList = async () => {
  loadingDirections.value = true;
  try {
    const response = await listDirection();
    if (response.code === 200 && response.rows) {
      directionOptions.value = response.rows;
    } else {
      directionOptions.value = [
        { directionId: 1, directionName: '后端开发' },
        { directionId: 2, directionName: '前端开发' },
        { directionId: 3, directionName: '鸿蒙开发' },
        { directionId: 4, directionName: 'C++' },
        { directionId: 5, directionName: '大数据' },
        { directionId: 6, directionName: 'UI设计' },
        { directionId: 7, directionName: '其他' }
      ];
      ElMessage.warning('方向列表加载失败，使用默认选项');
    }
  } catch (error) {
    console.error('加载方向列表失败:', error);
    directionOptions.value = [
      { directionId: 1, directionName: '后端开发' },
      { directionId: 2, directionName: '前端开发' },
      { directionId: 3, directionName: '鸿蒙开发' },
      { directionId: 4, directionName: 'C++' },
      { directionId: 5, directionName: '大数据' },
      { directionId: 6, directionName: 'UI设计' },
      { directionId: 7, directionName: '其他' },
    ];
    ElMessage.warning('方向列表加载失败，使用默认选项');
  } finally {
    loadingDirections.value = false;
  }
};

// 生命周期钩子
onMounted(() => {
  loadDirectionList();
});

// 重置表单
const resetForm = () => {
  recordFormRef.value.resetFields();
  fileList.value = [];
  form.result = ''; // 清空文件URL
  form.sumTime = ''; // 清空学习时长
  form.studyDate = ''; // 清空日期
  startTime.value = ''; // 清空开始时间
  endTime.value = ''; // 清空结束时间
};
</script>

<style scoped>
.mobile-form-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding-bottom: 80px;
}

.form-header {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  transform: skewY(-6deg);
  transform-origin: top left;
}

.header-content {
  position: relative;
  z-index: 1;
  text-align: center;
  padding-top: 60px;
  color: white;
}

.header-content h1 {
  font-size: 32px;
  font-weight: 600;
  margin: 0 0 8px 0;
}

.header-content p {
  font-size: 16px;
  opacity: 0.9;
  margin: 0;
}

.form-content {
  margin: -40px 20px 0;
  background: white;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 30px 20px;
}

.form-section {
  margin-bottom: 30px;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 20px 0;
}

.section-title .el-icon {
  margin-right: 8px;
  color: #667eea;
}

:deep(.mobile-input) {
  width: 100%;
}

:deep(.mobile-input .el-input__wrapper) {
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

:deep(.mobile-input .el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  border-color: #667eea;
}

:deep(.mobile-select) {
  width: 100%;
}

:deep(.mobile-select .el-select__wrapper) {
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
}

:deep(.mobile-date) {
  width: 100%;
}

:deep(.mobile-date .el-input__wrapper) {
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

:deep(.mobile-date .el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  border-color: #667eea;
}

:deep(.mobile-time) {
  width: 100%;
}

:deep(.mobile-time .el-input__wrapper) {
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

:deep(.mobile-time .el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  border-color: #667eea;
}

:deep(.mobile-datetime) {
  width: 100%;
}

:deep(.mobile-datetime .el-input__wrapper) {
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
}

:deep(.mobile-textarea .el-textarea__inner) {
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
  font-family: inherit;
}

:deep(.mobile-upload) {
  width: 100%;
}

:deep(.mobile-upload .el-upload-dragger) {
  padding: 40px 20px;
  border-radius: 12px;
  border: 2px dashed #dcdfe6;
  background: #fafbfc;
  transition: all 0.3s ease;
}

:deep(.mobile-upload .el-upload-dragger:hover) {
  border-color: #667eea;
  background: #f5f7ff;
}

.upload-icon {
  font-size: 48px;
  color: #909399;
  margin-bottom: 16px;
}

.upload-text {
  text-align: center;
}

.upload-title {
  font-size: 16px;
  color: #606266;
  margin-bottom: 8px;
}

.upload-tip {
  font-size: 14px;
  color: #909399;
}

.duration-display {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: #f0f9ff;
  border-radius: 8px;
  color: #0369a1;
  font-weight: 500;
}

.duration-display .el-icon {
  margin-right: 8px;
}

.location-btn {
  width: 100%;
  padding: 12px 24px;
  border-radius: 12px;
  font-size: 16px;
}

.form-actions {
  display: flex;
  gap: 16px;
  margin-top: 40px;
}

.submit-btn, .reset-btn {
  flex: 1;
  padding: 16px;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
}

.submit-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.success-content {
  text-align: center;
  padding: 20px;
}

.success-icon {
  font-size: 64px;
  color: #67c23a;
  margin-bottom: 16px;
}

.success-content h3 {
  font-size: 20px;
  color: #333;
  margin: 0 0 8px 0;
}

.success-content p {
  font-size: 16px;
  color: #666;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .form-content {
    margin: -40px 10px 0;
    padding: 20px 15px;
  }
  
  .header-content h1 {
    font-size: 28px;
  }
}
</style>
